<template>
    <div class="json-bean-container">
        <div class="control-panel">
            <n-select
                v-model:value="targetLang"
                :options="langOptions"
                class="lang-select"
                placeholder="选择目标语言"
            />
            <n-button @click="formatJson" :disabled="!inputJson">转换</n-button>
            <n-button @click="clearAll">清空</n-button>
        </div>

        <div class="content-panel">
            <!-- 输入区域 -->
            <div class="input-section">
                <div class="section-header">
                    <span>JSON</span>
                    <div class="actions">
                        <n-button quaternary size="small" @click="clearInput">
                            清空
                        </n-button>
                    </div>
                </div>
                <n-input
                    v-model:value="inputJson"
                    type="textarea"
                    :autosize="{ minRows: 10, maxRows: 15 }"
                    placeholder="请输入JSON字符串"
                />
            </div>

            <!-- 输出区域 -->
            <div class="output-section">
                <div class="section-header">
                    <span>{{ targetLang === 'java' ? 'Java类' : 'TypeScript接口' }}</span>
                    <div class="actions">
                        <n-button quaternary size="small" @click="copyOutput" :disabled="!outputText">
                            复制
                        </n-button>
                        <n-button quaternary size="small" @click="clearOutput" :disabled="!outputText">
                            清空
                        </n-button>
                    </div>
                </div>
                <n-input
                    v-model:value="outputText"
                    type="textarea"
                    :autosize="{ minRows: 10, maxRows: 15 }"
                    readonly
                    placeholder="转换结果将显示在这里"
                />
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import view from '@renderer/util/ui/ViewUtil'

// 目标语言
const targetLang = ref<'java' | 'typescript'>('java')
const langOptions = [
    { label: 'Java', value: 'java' },
    { label: 'TypeScript', value: 'typescript' }
]

// 输入输出
const inputJson = ref('')
const outputText = ref('')

// 格式化JSON
const formatJson = () => {
    try {
        const obj = JSON.parse(inputJson.value)
        inputJson.value = JSON.stringify(obj, null, 4)
        convertToClass()
    } catch (error) {
        view.alertErrorMessage('JSON格式错误')
    }
}

// 转换为类
const convertToClass = () => {
    try {
        const obj = JSON.parse(inputJson.value)
        if (targetLang.value === 'java') {
            outputText.value = generateJavaClass('Root', obj)
        } else {
            outputText.value = generateTypeScriptInterface('Root', obj)
        }
    } catch (error) {
        view.alertErrorMessage('转换失败')
        console.error('转换失败:', error)
    }
}

// 生成Java类
const generateJavaClass = (className: string, obj: any): string => {
    let result = `public class ${className} {\n`
    
    for (const [key, value] of Object.entries(obj)) {
        const type = getJavaType(value)
        if (type === 'Object') {
            // 为嵌套对象创建新类
            const nestedClassName = capitalize(key)
            result += generateJavaClass(nestedClassName, value) + '\n'
            result += `    private ${nestedClassName} ${key};\n`
        } else if (type.includes('List<')) {
            // 处理数组
            if (value.length > 0 && typeof value[0] === 'object') {
                const nestedClassName = capitalize(key.replace(/s$/, ''))
                result += generateJavaClass(nestedClassName, value[0]) + '\n'
            }
            result += `    private ${type} ${key};\n`
        } else {
            result += `    private ${type} ${key};\n`
        }
    }

    // 生成getter和setter
    for (const [key, value] of Object.entries(obj)) {
        const type = getJavaType(value)
        const capitalizedKey = capitalize(key)
        
        // Getter
        result += `\n    public ${type} get${capitalizedKey}() {\n`
        result += `        return ${key};\n`
        result += '    }\n'
        
        // Setter
        result += `\n    public void set${capitalizedKey}(${type} ${key}) {\n`
        result += `        this.${key} = ${key};\n`
        result += '    }\n'
    }

    result += '}\n'
    return result
}

// 生成TypeScript接口
const generateTypeScriptInterface = (interfaceName: string, obj: any): string => {
    let result = `interface ${interfaceName} {\n`
    
    for (const [key, value] of Object.entries(obj)) {
        const type = getTypeScriptType(value)
        if (type === 'object') {
            // 为嵌套对象创建新接口
            const nestedInterfaceName = capitalize(key) + 'Type'
            result = generateTypeScriptInterface(nestedInterfaceName, value) + '\n' + result
            result += `    ${key}: ${nestedInterfaceName};\n`
        } else if (type.includes('Array<')) {
            // 处理数组
            if (value.length > 0 && typeof value[0] === 'object') {
                const nestedInterfaceName = capitalize(key.replace(/s$/, '')) + 'Type'
                result = generateTypeScriptInterface(nestedInterfaceName, value[0]) + '\n' + result
            }
            result += `    ${key}: ${type};\n`
        } else {
            result += `    ${key}: ${type};\n`
        }
    }

    result += '}\n'
    return result
}

// 获取Java类型
const getJavaType = (value: any): string => {
    if (value === null) return 'Object'
    if (Array.isArray(value)) {
        if (value.length === 0) return 'List<Object>'
        return `List<${capitalize(getJavaType(value[0]))}>`
    }
    
    switch (typeof value) {
        case 'string': return 'String'
        case 'number':
            return Number.isInteger(value) ? 'Integer' : 'Double'
        case 'boolean': return 'Boolean'
        case 'object': return 'Object'
        default: return 'Object'
    }
}

// 获取TypeScript类型
const getTypeScriptType = (value: any): string => {
    if (value === null) return 'null'
    if (Array.isArray(value)) {
        if (value.length === 0) return 'any[]'
        return `Array<${getTypeScriptType(value[0])}>`
    }
    
    switch (typeof value) {
        case 'string': return 'string'
        case 'number': return 'number'
        case 'boolean': return 'boolean'
        case 'object': return 'object'
        default: return 'any'
    }
}

// 首字母大写
const capitalize = (str: string): string => {
    return str.charAt(0).toUpperCase() + str.slice(1)
}

// 监听语言变化
watch(targetLang, () => {
    if (inputJson.value.trim()) {
        convertToClass()
    }
})

// 复制输出
const copyOutput = async () => {
    try {
        await navigator.clipboard.writeText(outputText.value)
        view.alertSuccessMessage('复制成功')
    } catch {
        view.alertErrorMessage('复制失败')
    }
}

// 清空输入
const clearInput = () => {
    inputJson.value = ''
    outputText.value = ''
}

// 清空输出
const clearOutput = () => {
    outputText.value = ''
}

// 清空所有
const clearAll = () => {
    clearInput()
}
</script>

<style scoped>
.json-bean-container {
    height: 100%;
    padding: 16px;
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.control-panel {
    display: flex;
    gap: 16px;
    align-items: center;
}

.lang-select {
    width: 150px;
}

.content-panel {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 16px;
    min-height: 0;
}

.input-section,
.output-section {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 8px;
    min-height: 0;
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.actions {
    display: flex;
    gap: 8px;
}

:deep(.n-input) {
    font-family: monospace;
}
</style>